/**
 * Copyright 2009-2011 xiaonei.com All right reserved.
 * This software is the confidential and proprietary information of Xiaonei.com ("Confidential Information"). 
 * You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Xiaonei.com.
 * Create by XiaoNeiAntiSpamTeam
 *
 */

package com.xiaonei.testice.testamd.service;

import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import Ice.Current;

import com.xiaonei.testice.testamd.AMD_Printer_printString;
import com.xiaonei.testice.testamd._PrinterDisp;

/**
 * @ClassName: AMDPrinterI
 * @Description: AMD printer类
 * @author shaohui.liu shaohui.liu@opi-corp.com
 * @date Jan 28, 2010 12:13:00 AM
 * 
 */
public class AMDPrinterI extends _PrinterDisp {

    /**
     * 任务队列
     */
    private Queue<AMDPrinterJob> jobs = null;

    /**
     * 线程个数
     */
    private int numOfThread = 10;

    /**
     * 缓存的最大任务个数
     */
    private int maxCacheJobNum = 1000000;

    /**
     * 处理线程
     */
    private ExecutorService threadPool = Executors.newFixedThreadPool(numOfThread);

    public AMDPrinterI() {
        jobs = new LinkedBlockingQueue<AMDPrinterJob>();
    }

    /* (非 Javadoc)  
     * <p>Title: printString_async</p>
     * <p>Description: </p>
     * @param cb
     * @param message
     * @param current
     * @see com.xiaonei.testice.testamd._PrinterOperations#printString_async(com.xiaonei.testice.testamd.AMD_Printer_printString, java.lang.String, Ice.Current)
    */
    @Override
    public void printString_async(AMD_Printer_printString cb, String message, Current current) {
        if (jobs.size() < maxCacheJobNum) {
            jobs.add(new AMDPrinterJob(cb, message));
        } else {
            cb.ice_exception(new Exception("服务队列太长"));
        }
    }

    /**
     * 
     * @ClassName: AMDPrinterRunnable
     * @Description: AMDPrinter处理线程
     * @author shaohui.liu shaohui.liu@opi-corp.com
     * @date Feb 1, 2010 9:19:48 PM
     * 
     */
    class AMDPrinterRunnable implements Runnable {

        @Override
        public void run() {
            while (true) {
                if (!jobs.isEmpty()) {
                    AMDPrinterJob job = jobs.poll();
                    if (job == null) {
                        continue;
                    }
                    System.out.println(job.getMessage());
                    job.getCb().ice_response();
                }
            }
        }
    }
}
